package net.stogi.unicore.beyond.io.client.input.combofield;

import java.util.Arrays;

import net.stogi.unicore.beyond.api.model.InputDefinition;
import net.stogi.unicore.beyond.io.client.input.core.InputField;

import com.extjs.gxt.ui.client.widget.form.SimpleComboBox;
import com.google.gwt.user.client.ui.Widget;

public class ComboInputField implements InputField {

	protected final SimpleComboBox<String> field = new SimpleComboBox<String>();

	protected InputDefinition inputDefinition;

	public ComboInputField(InputDefinition inputDefinition) {
		this(inputDefinition.getInputType().getName());
		this.inputDefinition = inputDefinition;
		initField();
	}

	@SuppressWarnings("unused")
	private ComboInputField() {}

	private ComboInputField(String inputTypeName) {
		if (!"combofield".equals(inputTypeName)) {
			throw new IllegalArgumentException("Input definition is not type of 'combofield'");
		}
	}

	@Override
	public Widget asWidget() {
		return field;
	}

	@Override
	public String getValue() {
		// Return first selected.
		String value = null;
		
		if (!field.getSelection().isEmpty()) {
			value = field.getSelection().get(0).getValue();
		}
			
		return value;
	}

	@Override
	public void setValue(String value) {
		field.setSimpleValue(value);
	}

	private void initField() {
		field.setFieldLabel(inputDefinition.getName());
		field.setForceSelection(true);
		// Values of combo box.
		field.add(Arrays.asList(doParseValues(inputDefinition.getProperty("values").getValue())));
		// Can be empty.
		field.setAllowBlank(Boolean.parseBoolean(inputDefinition.getProperty("empty").getValue()));
	}
	
	private String[] doParseValues(String values) {
		return values.split(",");
	}

	@Override
	public void setError(String error) {
		if (error != null) {
			field.forceInvalid(error);
		}
		else {
			field.clearInvalid();
		}
	}
}
